require('dotenv').config();
const { OpenAI } = require('openai');
const info = require('./foodConfig');

class OpenAIManager {
    constructor() {
        // this.openaichat = new OpenAI({
        //     apiKey: process.env['ARK_API_KEY1'], 
        //     baseURL: 'https://ark.cn-beijing.volces.com/api/v3', 
        // });
        this.openaichat = new OpenAI({
            apiKey: process.env['ARK_API_KEY'],
            baseURL: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
        });
        //每一次的返回都比较慢，先存10条数据
        this.foodlist = info;
        this.checkFlag = 0;
        // this.checkFoodList();
    }
    checkFoodList() {
        this.checkFlag = 1;//正在请求中，不重复请求。
        const prompt = `你是一个营养专家，面对的是一个20岁到35岁的人群，经济条件一般，现在需要你帮他们规划日常三餐饭的配比信息。现在有一个人的情况如下：没有忌口，请帮忙配比近四天的三餐信息，其中食物不包含水果类，格式为：[{"breakfast":[{food:燕麦粥, value:膳食纤维}],"lunch"：……,"dinner":……},……]的json格式。1、food中不要举例子，比如"清炒时蔬（如白菜、西兰花等）"直接"清炒时蔬",2、除了json其他信息都不要返回，以免影响json解析。`;
        this.chat(prompt).then(res => {
            this.foodlist.push(...res);
            this.checkFlag = 0;
            if (this.foodlist.length <= 20) {
                this.checkFoodList();
            }
        });

    }
    async chat(prompt) {
        const sysCtn = '你是一个营养专家，面对的是一个20岁到35岁的人群，经济条件一般，现在需要你帮他们规划日常三餐饭的配比信息。';
        const completion = await this.openaichat.chat.completions.create({
            model: "deepseek-r1-distill-llama-70b",
            messages: [
                { role: 'system', content: sysCtn },
                { role: 'user', content: prompt },
            ],
            // model: 'ep-20250304150203-4kvql',
        });
        console.log(completion.choices[0]?.message?.content);
        return JSON.parse(completion.choices[0]?.message?.content);
    }
    getFood(aversion) {
        if (aversion != "") {
            return {
                "breakfast": this.getItemWithoutAversion(this.foodlist.breakfast, aversion),
                "lunch": this.getItemWithoutAversion(this.foodlist.lunch, aversion),
                "dinner": this.getItemWithoutAversion(this.foodlist.dinner, aversion),
            }
        } else
            return {
                "breakfast": this.foodlist.breakfast[Math.floor(Math.random() * this.foodlist.breakfast.length)],
                "lunch": this.foodlist.lunch[Math.floor(Math.random() * this.foodlist.lunch.length)],
                "dinner": this.foodlist.dinner[Math.floor(Math.random() * this.foodlist.dinner.length)],
            }
    }
    getItemWithoutAversion(list, aversion) {
        let gotIt = false, food = list[Math.floor(Math.random() * list.length)], index = -1;
        while (!gotIt) {
            index = 1;
            for (let i = 0; i < food.length; i++) {
                if (food[i].indexOf(aversion) > -1) {
                    index = 2;
                    i = food.length;
                }
            }
            if (index == 1) {
                gotIt = true;
            }
        }
        return food;
    }
}

module.exports = OpenAIManager;

